package top.wilsonlv.jaguar.oauth2.security.component;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import top.wilsonlv.jaguar.commons.data.encryption.util.EncryptionUtil;
import top.wilsonlv.jaguar.oauth2.security.properties.JaguarOauth2SecurityProperties;
import top.wilsonlv.jaguar.security.model.SecurityUser;
import top.wilsonlv.jaguar.security.util.SecurityUtil;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static top.wilsonlv.jaguar.oauth2.security.Oauth2SecurityConstant.*;

/**
 * @author lvws
 * @since 2021/6/29
 */
@Component
@RequiredArgsConstructor
public class FeignRequestInterceptor implements RequestInterceptor {

    private final JaguarOauth2SecurityProperties jaguarOauth2SecurityProperties;

    @SneakyThrows
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String serverId = jaguarOauth2SecurityProperties.getServerId();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = UUID.randomUUID().toString();

        Map<String, String[]> params = new HashMap<>();
        params.put(OPENFEIGN_PARAMETER_PRE + PARAMETER_SERVER_ID, new String[]{serverId});
        params.put(OPENFEIGN_PARAMETER_PRE + PARAMETER_TIMESTAMP, new String[]{timestamp});
        params.put(OPENFEIGN_PARAMETER_PRE + PARAMETER_NONCE, new String[]{nonce});
        for (String key : params.keySet()) {
            requestTemplate.header(key, params.get(key)[0]);
        }

        for (String key : requestTemplate.queries().keySet()) {
            Collection<String> values = requestTemplate.queries().get(key);
            String[] valueArray = new String[values.size()];
            params.put(key, valueArray);

            int i = 0;
            for (String value : values) {
                valueArray[i++] = URLDecoder.decode(value, StandardCharsets.UTF_8.name());
            }
        }

        String raw = EncryptionUtil.sortParams(params);
        String rawMd5 = EncryptionUtil.md5AsHex(raw);

        String sign = EncryptionUtil.signRsa(rawMd5, jaguarOauth2SecurityProperties.getServerPrivateKey());
        requestTemplate.header(OPENFEIGN_PARAMETER_PRE + PARAMETER_SIGN, sign);

        SecurityUser currentUser = SecurityUtil.getCurrentUser(false);
        if (currentUser != null && currentUser.getTenantId() != null) {
            requestTemplate.header("tenantId", currentUser.getTenantId().toString());
        }
    }

}
